package com.diandi.messages.util;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author maliming
 */
@Component
public class SmsUtils {
	// 消息队列
	private static Logger logger = LoggerFactory.getLogger(SmsUtils.class);
	private static Properties properties = new Properties();
	// 资源文件属性
	private static String sendUrl;
	private static String cdkey;
	private static String password;
	// 秒借 短信平台配置
	private static String mjsendUrl;
	private static String mjcdkey;
	private static String mjpassword;

	// ------------

	// 创建一个单线程的线程池
	private static ExecutorService executor = Executors.newSingleThreadExecutor();

	/**
	 * 系统加载
	 */
	@PostConstruct
	private void initSys() {
		try {
			InputStream inputStream = SmsUtils.class.getClassLoader().getResourceAsStream(
					"sms.properties");
			properties.load(inputStream);
			sendUrl = properties.getProperty("sendUrl");
			cdkey = properties.getProperty("cdkey");
			password = properties.getProperty("password");

			mjsendUrl = properties.getProperty("mjsendUrl");
			mjcdkey = properties.getProperty("mjcdkey");
			mjpassword = properties.getProperty("mjpassword");
		} catch (FileNotFoundException e) {
			logger.error("文件不存在！sms.properties");
		} catch (IOException e) {
			logger.error("文件sms.properties，读取错误");
		} catch (Exception e) {
			logger.error("获取属性异常：{}", e.getMessage());
		}
	}

	public static void executeTask(final String content, final List<String> mobiles) {
		executor.execute(new Runnable() {
			@Override
			public void run() {
				if (StringUtils.isNotBlank(content) && !mobiles.isEmpty()) {
					sendBatchSms(content, mobiles);
				}
			}
		});
	}



	/**
	 * 发送短信内容
	 *
	 * @param mobile
	 * @param content
	 */
	public static String sendSms(String mobile, String content) {
		try {
			String returnString = HttpSender.batchSend(sendUrl, cdkey, password, mobile, content,
					true, null, null);
			logger.info("手机号:【{}】发送短信成功:返回信息为{}", mobile, returnString);
			return returnString;
		} catch (Exception e) {
			logger.error("发送短信请求异常：{}", e.getMessage());
			return e.getMessage();
		}

	}

	public static String sendBatchSms(String content, List<String> list) {
		String mobile = "";
		for (String mobileNum : list) {
			mobile += mobileNum + ",";
		}
		try {
			String returnString = HttpSender.batchSend(sendUrl, cdkey, password, mobile, content,
					true, null, null);
			return returnString;
		} catch (Exception e) {
			logger.error("发送短信请求异常：{}", e.getMessage());
			return e.getMessage();
		}
	}


	/**
	 * 秒借发送短信内容
	 *
	 * @param mobile
	 * @param content
	 */
	public static void mjsendSms(String mobile, String content) {
		HttpClient httpClient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(mjsendUrl);
		try {
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("cdkey", mjcdkey));
			params.add(new BasicNameValuePair("password", mjpassword));
			params.add(new BasicNameValuePair("phone", mobile));
			params.add(new BasicNameValuePair("message", content));
			// params.add(new BasicNameValuePair("seqid",
			// DateUtil.getDateLong().toString()));
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
			httpPost.setEntity(entity);
			HttpResponse httpResponse = httpClient.execute(httpPost);
			System.out.println(httpResponse.getStatusLine().getStatusCode());
			if (httpResponse.getStatusLine().getStatusCode() != 200) {
				logger.error("MJ_发送短信请求返回码:code={}", httpResponse.getStatusLine().getStatusCode());
			}
			String resultXml = EntityUtils.toString(httpResponse.getEntity());
			if (StringUtils.isNotBlank(resultXml)) {
				Pattern pattern = Pattern.compile("<error>(.*)</error>");
				Matcher matcher = pattern.matcher(resultXml);
				String resultCode = "";
				while (matcher.find()) {
					resultCode = matcher.group(1);
				}
				if (resultCode.trim().equals(0)) {
					logger.info("MJ_手机号:【{}】发送短信成功", mobile);
				} else {
					logger.info("MJ_手机号:【{}】发短信返回的code：【{}】", mobile, resultCode);
				}
			}
			httpClient.getConnectionManager().shutdown();

		} catch (IOException e) {
			logger.error("发送短信请求异常：{}", e.getMessage());
		}

	}

}
